<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Request
 *
 * @author Jewel Tolentino
 */
class Request extends Database {

    //put your code here

    public $id;
    public $formName;
    public $referencePrefix;
    public $referenceType;
    public $fields;
    public $formId;
    public $data;
    public $trackNo;
    public $keywordFields;

    public function forMyApproval($companyID, $userID) {
        $requestCount = "";
        $forms = $this->query("SELECT * FROM tb_workspace WHERE company_id = {$this->escape($companyID)}", 'array');

        foreach ($forms as $form) {
            $strSQL = "SELECT * FROM " . $form['form_table_name'] . " WHERE Processor = {$this->escape($userID)}";
            $count = $this->query($strSQL, 'numrows');

            $requestCount += $count;
        }

        return $requestCount;
    }

    public function myRequests() {
        //TODO 
    }

    public function load($formId, $id) {
        $this->formId = $formId;
        $results = $this->query("SELECT form_table_name, reference_prefix, reference_type  FROM tb_workspace WHERE id = {$this->escape($formId)}", 'row');

        $this->formName = $results['form_table_name'];
        $this->referencePrefix = $results['reference_prefix'];
        $this->referenceType = $results['reference_type'];
        $this->id = $id;

        $fieldResults = $this->query("SELECT DISTINCT COLUMN_NAME FROM information_schema.columns WHERE TABLE_SCHEMA={$this->escape(DB_NAME)} AND TABLE_NAME ={$this->escape($this->formName)}", 'array');
        $this->fields = $fieldResults;
    }

    public function save() {
        //insert record
        $this->id = $this->insert($this->formName, $this->data);
        $conditionFields['ID'] = $this->id;

        //generate tracking number
        $trackNoField['TrackNo'] = library::getTrackNo($this, $this->referencePrefix, $this->referenceType, $this->id);
        $this->trackNo = $trackNoField['TrackNo'];
        $this->update($this->formName, $trackNoField, $conditionFields);
    }

    public function modify() {
        //update record
        $conditionFields['ID'] = $this->id;
        $this->update($this->formName, $this->data, $conditionFields);
    }

    public function createFieldLevelLogs($fields) {
        $auth = Auth::getAuth('current_user');
        $date = $this->currentDateTime();
        $fieldSQL = array();

        foreach ($fields as $field) {
            array_push($fieldSQL, $field);
        }

        $result = $this->query("SELECT " . join(",", $fieldSQL) . " FROM {$this->formName} WHERE ID={$this->id}");


        foreach ($result as $key => $value) {
            foreach ($fields as $field) {
                $oldValue = $value[$field];
                $newValue = $this->data[$field];

                if ($oldValue != $newValue) {
                    $logDoc = new Request_Log($this);
                    $logDoc->form = new Form($this, $this->formId);
                    $logDoc->request_id = $this->id;
                    $logDoc->details = $field . ' has been changed from "' . $oldValue . '" to "' . $newValue . '"';
                    $logDoc->created_by = new Person($this, $auth['id']);
                    $logDoc->date_created = $date;
                    $logDoc->save();
                }
            }
        }
    }

    public function processWF($currentUser) {
        if ($currentUser) {
            $auth = $this->query("SELECT * FROM tbuser WHERE id = {$currentUser->id}", "row");
        } else {
            $auth = Auth::getAuth('current_user');
        }

        do {
            $processWF = $this->query("SELECT
                FRM.*,
                WFO.type_rel as NodeType, 
                WFO.Processor as Processor,
                PROCESSOR.department_position_level as Department_Position_Level,
                PROCESSOR.department_id as Processor_Department_Id,
                WFO.Status as Status,
                WFO.buttonStatus as Buttons,
                WFO.ProcessorType as ProcessorType, 
                WFO.condition_return as ConditionAction,
                WFO.field as Field,
                WFO.operator as Operator,
                WFO.field_value as FieldValue,
                WFO.fieldEnabled as WF_FieldEnabled,
                WFO.fieldRequired as WF_FieldRequired,
                WFO.fieldHiddenValue as WF_FieldHiddenValue,
                WFO.email as Email,
                WFO.sms as SMS,
                WFO.json as WorkflowData
                FROM " . $this->formName .
                    " FRM LEFT JOIN tbworkflow WF 
                ON WF.id = FRM.Workflow_Id
                LEFT JOIN tbworkflow_objects WFO
                ON WFO.Workflow_Id = WF.Id AND WFO.Object_Id = FRM.Node_Id
                LEFT JOIN tbuser PROCESSOR
                ON PROCESSOR.Id = FRM.Processor
                WHERE FRM.Id = {$this->escape($this->id)}"
                    , "row");

            $node_type = $processWF['NodeType'];

            if ($node_type == 3) {
                //conditions
                $jsonAction = json_decode($processWF['ConditionAction'], true);
                $trueNode = $jsonAction['True']['child_id'];
                $falseNode = $jsonAction['False']['child_id'];

                $field = $processWF['Field'];
                $operator = $processWF['Operator'];
                $field_value = $processWF['FieldValue'];
                $form_field_value = $processWF[$field];

                switch ($operator) {
                    case '==';
                        if ($form_field_value == $field_value) {
                            $targetNode = $trueNode;
                        } else {
                            $targetNode = $falseNode;
                        }
                        break;
                    case '<':
                        if (floatval($form_field_value) < floatval($field_value)) {
                            $targetNode = $trueNode;
                        } else {
                            $targetNode = $falseNode;
                        }
                        break;
                    case '>':
                        if (floatval($form_field_value) > floatval($field_value)) {
                            $targetNode = $trueNode;
                        } else {
                            $targetNode = $falseNode;
                        }
                        break;
                    case '<=':
                        if (floatval($form_field_value) <= floatval($field_value)) {
                            $targetNode = $trueNode;
                        } else {
                            $targetNode = $falseNode;
                        }
                        break;
                    case '>=':
                        if (floatval($form_field_value) >= floatval($field_value)) {
                            $targetNode = $trueNode;
                        } else {
                            $targetNode = $falseNode;
                        }
                        break;
                    case '!=':
                        if ($form_field_value != $field_value) {
                            $targetNode = $trueNode;
                        } else {
                            $targetNode = $falseNode;
                        }
                        break;
                }

                $wfFields['Node_Id'] = $targetNode;

                $conditionFields['ID'] = $this->id;
                $this->update($this->formName, $wfFields, $conditionFields);
            } else {
                //condition loop will stop after this code

                $wfFields['Status'] = $processWF['Status'];
                $wfFields['LastAction'] = $processWF['Buttons'];
                $wfFields['fieldEnabled'] = $processWF['WF_FieldEnabled'];
                $wfFields['fieldRequired'] = $processWF['WF_FieldRequired'];
                $wfFields['fieldHiddenValues'] = $processWF['WF_FieldHiddenValue'];

                $workflowData = json_decode($processWF['WorkflowData'], true);
                $trigger_data = $workflowData['workflow-trigger'];

                foreach ($trigger_data as $row) {
                    if ($row['workflow-trigger-action'] == 'Create') {
                        //form diverge
                        // $this->diverge($row);
                        $this->createResponse($row);
                    } else if ($row['workflow-trigger-action'] == 'Update Response') {
                        //form diverge
                        // $this->diverge($row);
                        $this->updateResponse($row);
                    } else {
                        //update keyword
                        $this->updateKeyword($row);
                    }
                }

                $processor_type = $processWF['ProcessorType'];

                if ($processor_type == 1) {//head/assistant head
                    $user_department_position_level = $processWF['Department_Position_Level'];
                    $processorType = $processWF['Processor'];
                    $processor_department = $processWF['Processor_Department_Id'];

                    do {
                        //loop until processor is found

                        $parent_department = $this->query("SELECT PARENT_DEPARTMENT.id as Parent_Department FROM tborgchartobjects CHILD_DEPARTMENT
                        LEFT JOIN tborgchartline DEPARMENTLINE 
                        ON DEPARMENTLINE.child = CHILD_DEPARTMENT.object_id AND DEPARMENTLINE.orgChart_id = CHILD_DEPARTMENT.orgChart_id 
                        LEFT JOIN tborgchartobjects PARENT_DEPARTMENT 
                        ON PARENT_DEPARTMENT.object_id = DEPARMENTLINE.parent AND PARENT_DEPARTMENT.orgChart_id  = DEPARMENTLINE.orgChart_id
                        WHERE CHILD_DEPARTMENT.id ={$this->escape($processor_department)} LIMIT 1 ", "row");

                        $parent_department_id = $parent_department['Parent_Department'];

                        if ($user_department_position_level == 1) {
                            $processor_department = $parent_department_id;
                        }

                        if ($user_department_position_level == 2 && $processorType == 2) {
                            $processor_department = $parent_department_id;
                        }

                        $processor_result = $this->query("SELECT json
                                    FROM tborgchartobjects DEPARTMENT WHERE id = {$this->escape($processor_department)}", "row");


                        if ($processorType == 1) {
                            $department_data = json_decode($processor_result['json'], true);
                            $processor = $department_data['orgchart_user_head'][0];

                            if ($processor == '' || $processor == 'null' || $processor == null || $processor == 0) {//if head not found request will be forwarded to assistant head of the parent department
                                $processor_department = $parent_department_id;
                                $processorType = 2;
                            }
                        } else {
                            //assistant head
                            $department_data = json_decode($processor_result['json'], true);
                            $processor = $department_data['orgchart_dept_assistant'][0];

                            if ($processor == '' || $processor == 'null' || $processor == null || $processor == 0) {//if assistant head not found request will be forwarded to head
                                $processorType = 1;
                            }
                        }
                    } while (($processor == '' || $processor == 'null' || $processor == null || $processor == 0) && $parent_department_id != '');

                    if ($processor == '' || $processor == 'null' || $processor == null || $processor == 0) {
                        //if the system detects that the there's no next processor
                        $wfFields['Processor'] = $processWF['Requestor'];
                        ;
                    } else {
                        $wfFields['Processor'] = $processor;
                    }
                }

                if ($processor_type == 2) {//position
                    $processor_result = $this->query("SELECT group_concat(user_processor.id separator ',') as Processor
                        FROM tbuser user_processor 
                        WHERE user_processor.Position = {$this->escape($processWF['Processor'])} AND company_id={$auth['company_id']}", "row");

                    $wfFields['Processor'] = $processor_result['Processor'];
                }

                if ($processor_type == 3) {//Specific User
                    $wfFields['Processor'] = $processWF['Processor'];
                }

                if ($processor_type == 4) {//Requestor
                    $wfFields['Processor'] = $processWF['Requestor'];
                }

                if ($processor_type == 5) {//Computed Field
                    $field_display_name = $this->query("SELECT " . $processWF['Processor'] .
                            " as Display_name FROM " . $this->formName . " WHERE id = {$this->id}", "row");

                    $processor_result = $this->query("SELECT id as Processor FROM tbuser
                        WHERE Display_Name = {$this->escape($field_display_name['Display_name'])} AND company_id={$auth['company_id']}", "row");

                    $wfFields['Processor'] = $processor_result['Processor'];
                }

                //users editors
                $users = $workflowData['users'];
                $editors = $users["user_editor"];
                $viewers = $users["user_viewer"];
                $wf_Editors = array();
                $wf_Viewers = array();

                if ($editors["requestor"]) {
                    array_push($wf_Editors, $processWF['Requestor']);
                }


                foreach ($editors["departments"] as $department_id) {
                    $department_users = functions::getUsers("WHERE department_id = {$department_id} AND company_id={$auth['company_id']}");
                    foreach ($department_users as $department_user) {
                        array_push($wf_Editors, $department_user->id);
                    }
                }

                foreach ($editors["positions"] as $position) {
                    $position_users = functions::getUsers("WHERE position = {$this->escape($position)} AND company_id={$auth['company_id']}");
                    foreach ($position_users as $position_user) {
                        array_push($wf_Editors, $position_user->id);
                    }
                }

                $wf_Editors = array_merge($wf_Editors, $editors["users"]);
                //users viewer
                if ($viewers["requestor"]) {
                    array_push($wf_Viewers, $processWF['Requestor']);
                }


                foreach ($viewers["departments"] as $department_id) {
                    $department_users = functions::getUsers("WHERE department_id = {$department_id} AND company_id={$auth['company_id']}");
                    foreach ($department_users as $department_user) {
                        array_push($wf_Viewers, $department_user->id);
                    }
                }

                foreach ($viewers["positions"] as $position) {
                    $position_users = functions::getUsers("WHERE position = {$this->escape($position)} AND company_id={$auth['company_id']}");
                    foreach ($position_users as $position_user) {
                        array_push($wf_Viewers, $position_user->id);
                    }
                }
                $wf_Viewers = array_merge($wf_Viewers, $viewers["users"]);

                $wfFields["Editor"] = join(",", $wf_Editors);
                $wfFields["Viewer"] = join(",", $wf_Viewers);

                $conditionFields['ID'] = $this->id;

                $this->update($this->formName, $wfFields, $conditionFields);

                //send mail
                $this->sendMail($processWF, $wfFields);
                //send sms
                $this->sendSMS($processWF, $wfFields);
                //save audit log
                $this->saveLog($wfFields);
                //create notification
                $this->createNotification($wfFields);
            }
        } while ($node_type == 3);
    }

    public function createNotification($wfFields) {
        $auth = Auth::getAuth('current_user');

        $processors = split(",", $wfFields['Processor']);

        foreach ($processors as $processor) {
            notifications::insertNofiRequest($this->id, $auth['id'], $this->formName, $processor);
        }
    }

    public function saveLog($wfFields) {
        $auth = Auth::getAuth('current_user');

        $date = $this->currentDateTime();
        $logDoc = new Request_Log($this);
        $logDoc->form = new Form($this, $this->formId);
        $logDoc->request_id = $this->id;
        $logDoc->details = $wfFields['Status'];
        $logDoc->created_by = new Person($this, $auth['id']);
        $logDoc->date_created = $date;
        $logDoc->save();
    }

    public function sendMail($processWF, $wfFields) {
        $auth = Auth::getAuth('current_user');
        //send mail
        $trackingNo = $processWF['TrackNo'];
        $emailJSON = $processWF['Email'];
        $requestor = $processWF['Requestor'];
        $processor = $wfFields['Processor'];

        $personDoc = new Person($this, $requestor);
        $processorDoc = new Person($this, $processor);

        $emailArr = json_decode($emailJSON, true);
        $recipients = array();
        $recipient_department_users = array();
        $recipient_position_users = array();
        $cc = array();
        $cc_department_users = array();
        $cc_position_users = array();
        $bcc = array();
        $bcc_department_users = array();
        $bcc_position_users = array();


        //to
        $recipient_department = $emailArr['email_recpient']['departments'];
        $recipient_position = $emailArr['email_recpient']['positions'];
        $recipient_users = $emailArr['email_recpient']['users'];
        $recipient_requestor = $emailArr['email_recpient']['requestor'];
        $recipient_processor = $emailArr['email_recpient']['processor'];


        //per department
        foreach ($recipient_department as $deparment) {
            array_push($recipient_department_users, functions::getUsers("WHERE department_id ={$this->escape($deparment)}"));
        }

        foreach ($recipient_department_users as $department_users) {
            foreach ($department_users as $userDoc) {
                $recipients[$userDoc->email] = $userDoc->display_name;
            }
        }

        //per position
        foreach ($recipient_position as $position) {
            array_push($recipient_position_users, functions::getUsers("WHERE position ={$this->escape($position)} AND company_id={$this->escape($auth['company_id'])}"));
        }

        foreach ($recipient_position_users as $position_users) {
            foreach ($position_users as $userDoc) {
                $recipients[$userDoc->email] = $userDoc->display_name;
            }
        }

        //per user
        foreach ($recipient_users as $id) {
            $userDoc = new Person($this, $id);
            $recipients[$userDoc->email] = $userDoc->display_name;
        }

        //requestor
        if ($recipient_requestor == 1) {
            $requestorDoc = new Person($this, $requestor);
            $recipients[$requestorDoc->email] = $requestorDoc->display_name;
        }

        //processor
        if ($recipient_processor == 1) {
            $processorDoc = new Person($this, $processor);
            $recipients[$processorDoc->email] = $processorDoc->display_name;
        }

        //cc
        $cc_department = $emailArr['email_cc']['departments'];
        $cc_position = $emailArr['email_cc']['positions'];
        $cc_users = $emailArr['email_cc']['users'];
        $cc_requestor = $emailArr['email_cc']['requestor'];
        $cc_processor = $emailArr['email_cc']['requestor'];

        //per department
        foreach ($cc_department as $deparment) {
            array_push($cc_department_users, functions::getUsers("WHERE department_id ={$this->escape($deparment)}"));
        }

        foreach ($cc_department_users as $department_users) {
            foreach ($department_users as $userDoc) {
                $cc[$userDoc->email] = $userDoc->display_name;
            }
        }

        //per position
        foreach ($cc_position as $position) {
            array_push($cc_position_users, functions::getUsers("WHERE position ={$this->escape($position)} AND company_id={$this->escape($auth['company_id'])}"));
        }

        foreach ($cc_position_users as $position_users) {
            foreach ($position_users as $userDoc) {
                $cc[$userDoc->email] = $userDoc->display_name;
            }
        }

        //per user
        foreach ($cc_users as $id) {
            $userDoc = new Person($this, $id);
            $cc[$userDoc->email] = $userDoc->display_name;
        }

        //requestor
        if ($cc_requestor == 1) {
            $requestorDoc = new Person($this, $requestor);
            $cc[$requestorDoc->email] = $requestorDoc->display_name;
        }

        //processor
        if ($cc_processor == 1) {
            $processorDoc = new Person($this, $processor);
            $cc[$processorDoc->email] = $processorDoc->display_name;
        }

        //bcc
        $bcc_department = $emailArr['email_bcc']['departments'];
        $bcc_position = $emailArr['email_bcc']['positions'];
        $bcc_users = $emailArr['email_bcc']['users'];
        $bcc_requestor = $emailArr['email_bcc']['requestor'];
        $bcc_processor = $emailArr['email_bcc']['requestor'];

        //per department
        foreach ($bcc_department as $deparment) {
            array_push($bcc_department_users, functions::getUsers("WHERE department_id ={$this->escape($deparment)}"));
        }

        foreach ($bcc_department_users as $department_users) {
            foreach ($department_users as $userDoc) {
                $bcc[$userDoc->email] = $userDoc->display_name;
            }
        }

        //per position
        foreach ($bcc_position as $position) {
            array_push($bcc_position_users, functions::getUsers("WHERE position ={$this->escape($position)} AND company_id={$this->escape($auth['company_id'])}"));
        }

        foreach ($bcc_position_users as $position_users) {
            foreach ($position_users as $userDoc) {
                $bcc[$userDoc->email] = $userDoc->display_name;
            }
        }

        //per user
        foreach ($bcc_users as $id) {
            $userDoc = new Person($this, $id);
            $bcc[$userDoc->email] = $userDoc->display_name;
        }

        //requestor
        if ($bcc_requestor == 1) {
            $requestorDoc = new Person($this, $requestor);
            $bcc[$requestorDoc->email] = $requestorDoc->display_name;
        }

        //processor
        if ($bcc_processor == 1) {
            $processorDoc = new Person($this, $processor);
            $bcc[$processorDoc->email] = $processorDoc->display_name;
        }

        //subject and body
        $subject_type = $emailArr['email-title-type'];
        $subject_message = $emailArr['title'];
        $body_type = $emailArr['email-message-type'];
        $body_message = $emailArr['message'];
        $requestFormDoc = new Form($this, $this->formId);

        if ($subject_type == 0) {
            $subject = $emailArr['title'];
        } else {
            $formulaDoc = new Formula($emailArr['title']);
            $formulaDoc->setSourceForm($requestFormDoc->form_name, "*", array(
                array("FieldName" => "TrackNo",
                    "Operator" => "=",
                    "Value" => $this->trackNo))
            );

            $subject = $formulaDoc->evaluate();
        }

        if ($body_type == 0) {
            $message = $emailArr['message'];
        } else {
            $formulaDoc = new Formula($emailArr['message']);
            $formulaDoc->setSourceForm($requestFormDoc->form_name, "*", array(
                array("FieldName" => "TrackNo",
                    "Operator" => "=",
                    "Value" => $this->trackNo))
            );

            $message = $formulaDoc->evaluate();
        }

        $from = "formalistics@gmail.com";
        $from_title = "Formalistics Web Application";
        $company_id = $auth['company_id'];
        $formID = $this->formId;
        $requestID = $this->id;

        $mail_info = array(
            "To" => $recipients,
            "CC" => $cc,
            "BCC" => $bcc,
            "From" => $from,
            "Title" => $subject,
            "From_Title" => $from_title,
            "Body" => $message,
            "Company_Id" => $company_id,
            "TrackNo" => $trackingNo,
            "Form_Id" => $formID,
            "Request_Id" => $requestID,
            "Requestor_name" => $personDoc->first_name . " " . $personDoc->last_name,
            "Processor_name" => $processorDoc->first_name . " " . $processorDoc->last_name,
        );

        $emailDoc = new Mail_Notification();
        $json_decode = Settings::noti_settings($processor, 'notifications');

        $json_request = $json_notifications['Request'];
        if ($json_request[0] == 1) {
            $emailDoc->workflow_notify_user($mail_info);
        }
        //$json_decode = Settings::noti_settings($processor,'notifications');
        //$json_notifications = $json_decode[0]['notifications'];
        //$json_request = $json_notifications['Request'];
        //if($json_request[0]==1){
        $emailDoc->workflow_notify_user($mail_info);
        //}
    }

    public function sendSMS($processWF, $wfFields) {
        $auth = Auth::getAuth('current_user');
        //send sms
        $smsArr = json_decode($processWF['SMS'], true);
        $sms_recipients = array();

        $sms_recipient_department = $smsArr['departments'];
        $sms_recipient_position = $smsArr['positions'];
        $sms_recipient_users = $smsArr['users'];
        $sms_recipient_requestor = $smsArr['requestor'];
        $sms_recipient_processor = $smsArr['processor'];
        $sms_recipient_contact = $smsArr['contact'];


        if ($smsArr['message-type'] == '0') {
            $message = $smsArr['message'];
        } else {
            $requestFormDoc = new Form($this, $this->formId);
            $formulaDoc = new Formula($smsArr['message']);
            $formulaDoc->setSourceForm($requestFormDoc->form_name, "*", array(
                array("FieldName" => "TrackNo",
                    "Operator" => "=",
                    "Value" => $this->trackNo))
            );

            $message = $formulaDoc->evaluate();
        }

        $sms_recipient_department_users = array();
        $sms_recipient_position_users = array();
        //per department
        foreach ($sms_recipient_department as $deparment) {
            array_push($sms_recipient_department_users, functions::getUsers("WHERE department_id ={$this->escape($deparment)}"));
        }

        foreach ($sms_recipient_department_users as $department_users) {
            foreach ($department_users as $userDoc) {
                array_push($sms_recipients, $userDoc->contact_number);
            }
        }

        //per position
        foreach ($sms_recipient_position as $position) {
            array_push($sms_recipient_position_users, functions::getUsers("WHERE position ={$this->escape($position)} AND company_id={$this->escape($auth['company_id'])}"));
        }

        foreach ($sms_recipient_position_users as $position_users) {
            foreach ($position_users as $userDoc) {
                array_push($sms_recipients, $userDoc->contact_number);
            }
        }

        //per user
        foreach ($sms_recipient_users as $id) {
            $userDoc = new Person($this, $id);
            array_push($sms_recipients, $userDoc->contact_number);
        }

        //requestor
        if ($sms_recipient_requestor) {
            $requestorDoc = new Person($this, $processWF['Requestor']);
            array_push($sms_recipients, $requestorDoc->contact_number);
        }

        //processor
        if ($sms_recipient_processor) {
            $processorDoc = new Person($this, $wfFields['Processor']);
            array_push($sms_recipients, $processorDoc->contact_number);
        }

        //contact_number
        if ($sms_recipient_contact != '') {
            $sms_recipient_contact_arr = split(';', $sms_recipient_contact);
            foreach ($sms_recipient_contact_arr as $contact_number) {
                array_push($sms_recipients, $contact_number);
            }
        }

        foreach ($sms_recipients as $number) {
            $smsDoc = new SMS($number, $message);
            $smsDoc->send();
        }
    }

    public function updateKeyword($workflowData) {
        $auth = Auth::getAuth('current_user');

        $keyword_update = $workflowData['workflow-trigger-fields-update'];
        $keyword_filter = $workflowData['workflow-trigger-fields-filter'];
        $keyword_operator = $workflowData['workflow-trigger-operator'];
        $quantity_to_update = floatval($this->data[$keyword_update]);

        foreach ($this->keywordFields as $key) {
            if ($key['Field'] == $keyword_filter) {
                $keywords = functions::getKeywords("WHERE ValueCode={$this->escape($key['Code'])} AND company_id={$this->escape($auth['company_id'])}");

                foreach ($keywords as $keywordDoc) {
                    $quantity_old_value = floatval($keywordDoc->quantity);

                    switch ($keyword_operator) {
                        case 'Addition':
                            $quantity_new_value = floatval($quantity_to_update) + floatval($quantity_old_value);

                            break;
                        case 'Subtraction':
                            $quantity_new_value = floatval($quantity_old_value) - floatval($quantity_to_update);

                            break;

                        case 'Multiplication':
                            $quantity_new_value = floatval($quantity_old_value) * floatval($quantity_to_update);

                            break;
                        case 'Division':
                            $quantity_new_value = floatval($quantity_old_value) / floatval($quantity_to_update);

                            break;
                    }

                    $keywordDoc->quantity = $quantity_new_value;
                    $keywordDoc->update();
                }
            }
        }
    }

    public function createResponse($workflowData) {
//        $auth = Auth::getAuth('current_user');
//        $date = $this->currentDateTime();
//        $form_id = $workflowData['workflow-form-trigger'];
//        $actions = $workflowData['workflow-field_formula'];
//
//        $requestFormDoc = new Form($this, $this->formId);
//        $formDoc = new Form($this, $form_id);
//        $personDoc = new Person($this, $auth['id']);
//
//
//        $result = array();
//
//        $result['Requestor'] = $auth['id'];
//        $result['Processor'] = $auth['id'];
//        $result['Status'] = 'Draft';
//        $result['imported'] = '1';
//        $result['DateCreated'] = $date;
//        $result['DateUpdated'] = $date;
//
//        foreach ($actions as $key) {
//            $field_name = $key['workflow-field-update'];
//            $formula = $key['workflow-field-formula'];
//
//            $formulaDoc = new Formula($formula);
//
//            $formulaDoc->setSourceForm($requestFormDoc->form_name, "*", array(
//                array("FieldName" => "TrackNo",
//                    "Operator" => "=",
//                    "Value" => $this->trackNo))
//            );
//            $returnValue = $formulaDoc->evaluate();
//
//            $result[$field_name] = $returnValue;
//        }
//
//        $requestDoc = new Request();
//        $requestDoc->load($form_id, '0');
//        $requestDoc->data = $result;
//        $requestDoc->save();
//
//        $requestLog = new Request_Log($this);
//        $requestLog->form = $formDoc;
//        $requestLog->request_id = $requestDoc->id;
//        $requestLog->details = 'Created from ' . $this->formName . ' with Tracking Number : ' . $this->trackNo;
//        $requestLog->created_by = $personDoc;
//        $requestLog->date_created = $date;
//        $requestLog->save();

        Response::create($this, $workflowData);
    }

    public function updateResponse($workflowData) {
        $auth = Auth::getAuth('current_user');
        $date = $this->currentDateTime();
        $form_id = $workflowData['workflow-form-trigger'];
        $reference_field = $workflowData['workflow-ref-field'];
        $actions = $workflowData['workflow-field_formula'];

        $requestFormDoc = new Form($this, $this->formId);
        $formDoc = new Form($this, $form_id);
        $personDoc = new Person($this, $auth['id']);

        $result = array();
        foreach ($actions as $key) {
            $field_name = $key['workflow-field-update'];
            $formula = $key['workflow-field-formula'];


            $formulaDoc = new Formula($formula);

            $formulaDoc->setSourceForm($requestFormDoc->form_name, "*", array(
                array("FieldName" => "TrackNo",
                    "Operator" => "=",
                    "Value" => $this->trackNo))
            );

            $returnValue = $formulaDoc->evaluate();

            $result[$field_name] = $returnValue;
        }


        $reference_field_value = $this->data[$reference_field];
        $request_row = $this->query("SELECT ID FROM " . $formDoc->form_table_name . " WHERE TrackNo = {$this->escape($reference_field_value)}", "row");

        $requestDoc = new Request();
        $requestDoc->load($form_id, $request_row['ID']);
        $requestDoc->data = $result;
        $requestDoc->modify();

        $requestLog = new Request_Log($this);
        $requestLog->form = $formDoc;
        $requestLog->request_id = $requestDoc->id;
        $requestLog->details = 'Updated from ' . $this->formName . ' with Tracking Number : ' . $this->trackNo;
        $requestLog->created_by = $personDoc;
        $requestLog->date_created = $date;
        $requestLog->save();
    }

}

?>
